<template>
  <div class="main_box" style="padding-right: 10px" v-loading="loading" element-loading-text="正在处理">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ title }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>

      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item label="呼叫器名称" prop="equipName" v-if="!batchAdd">
            <el-input v-model="dataForm.equipName" @keydown.native="keydown($event)"></el-input>
          </el-form-item>
          <el-form-item label="MAC地址" prop="equipMac" v-if="!batchAdd">
            <el-input v-model="dataForm.equipMac"></el-input>
          </el-form-item>
          <el-form-item label="呼叫器类型" prop="beeperType">
            <el-select class="readonly" :disabled="batchAdd" v-model="dataForm.beeperType" clearable
                       filterable>
              <el-option v-for="item in beeperTypeList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="呼叫器版本" prop="beeperVersion" v-if="!batchAdd">
            <el-select @change="setLinkway" v-model="dataForm.beeperVersion" clearable filterable>
              <el-option v-for="item in beeperVersionList" :key="item.id" :value="item.id"
                         :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="连网方式" prop="linkWay">
            <el-select @change="watchLinkway" :disabled="dataForm.beeperVersion===1" class="readonly"
                       v-model="dataForm.linkWay" clearable
                       filterable>
              <el-option v-for="item in linkWayLists" :key="item.value" :value="item.value"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="识别救命后的操作方式" v-if="dataForm.beeperVersion > 1">
            <el-radio-group v-model="dataForm.helpFlag">
              <el-radio :label="1">发送10秒录音</el-radio>
              <el-radio :label="2">拨打客服电话</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="呼叫器分类" prop="beeperClassify">
            <el-select v-model="dataForm.classifyId" clearable filterable>
              <el-option v-for="item in beeperClassifyList" :label="item.name" :value="item.id" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务员" prop="saleUserId">
            <el-select v-model="dataForm.saleUserId" clearable filterable>
              <el-option v-for="item in saleUserList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收货地址设置" prop="addressType">
            <el-select v-model="dataForm.addressType" clearable filterable>
              <el-option v-for="item in $Options.addressTypeList" :key="item.id" :value="item.id"
                         :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收货信息的填写方式">
            <el-radio-group v-model="dataForm.requireAddress"
                            :disabled="!!(dataForm.addressType === 1 || dataForm.addressType === 3)">
              <el-radio :label="1">呼叫器绑定时</el-radio>
              <el-radio :label="2">呼叫器下单时</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否开放搜索" v-if="dataForm.beeperType === 1">
            <el-radio-group v-model="dataForm.openSearch">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="地区" prop="streetIds">
            <Region ref="region" :streetValues="dataForm.streetIds" @regionChange="handleItemChange"
                    :isChangeOnSelect="true"></Region>
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select v-model="dataForm.villageId" @change="handleVillageChange" @focus="handleVillageFocus" clearable>
              <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门牌号" prop="residentAddress" v-if="!batchAdd">
            <el-cascader v-model="dataForm.residentAddress" :props="{ value: 'id', label: 'name' }"
                         :options="residentAddressList" clearable filterable placeholder="请选择门牌号"></el-cascader>
          </el-form-item>
          <!-- <el-form-item label="门牌号" prop="houseNumber" v-if="!batchAdd">
            <el-input v-model="dataForm.houseNumber"></el-input>
          </el-form-item> -->
          <el-form-item label="设备电话号" prop="equipPhone">
            <el-input type="text" v-model="dataForm.equipPhone"></el-input>
          </el-form-item>
          <el-form-item label="经度" prop="longitude" v-if="!batchAdd">
            <el-input type="number" v-model="dataForm.longitude"></el-input>
          </el-form-item>
          <el-form-item label="纬度" prop="latitude" v-if="!batchAdd">
            <el-input type="number" v-model="dataForm.latitude"></el-input>
            <el-button type="text" @click="getLngLat(1)">百度地图</el-button>
            <el-button type="text" @click="getLngLat(2)">腾讯地图</el-button>
          </el-form-item>
          <el-form-item prop="customerId" label="主用户" v-if="batchAdd">
            <el-select v-model="dataForm.customerId" clearable filterable>
              <el-option v-for="item in userList" :value="item.id"
                         :label="item.value ? item.name + ' - ' + item.value : item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="详细地址" prop="address">
            <el-input v-model="dataForm.address" clearable>

            </el-input>
            <div style="color:red">不包含省市区街道</div>
          </el-form-item> -->
          <el-form-item label="备 注 " prop="remark">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
          <el-form-item prop="siteUrl" label="地图图片">
            <upload-img class="upload-img" @uploadFileList="getsiteUrl" folder="beeperSitefile">
              <img v-if="dataForm.siteUrl" width="100%" :src="dataForm.siteUrl" alt=""/>
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.siteUrl"></i>
                <div v-if="!dataForm.siteUrl" class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
              </div>
            </upload-img>
          </el-form-item>
        </el-row>
        <el-row>
          <div class="tit" style="margin-bottom: 10px">
            <h2>界面设置</h2>
          </div>
          <tip-form-item label="呼叫器内容显示" prop="showLevel"
                         tip="小程序首页展示内容只有精选还是有精选和全部，选全部两者都显示">
            <el-select v-model="dataForm.showLevel" clearable filterable>
              <el-option v-for="item in showLevelList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </tip-form-item>
          <tip-form-item label="默认进入" prop="defaultOpen" tip="进入首页显示的是精选还是全部的内容">
            <el-select v-model="dataForm.defaultOpen" clearable :disabled="dataForm.showLevel ? true : false">
              <el-option v-for="item in defaultOpenList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <div slot="aa" slot-scope="a">
              {{ a }}
            </div>
          </tip-form-item>
          <tip-form-item label="按钮一行数" prop="btnLineNum" tip="首页按钮一行的显示数量">
            <el-select v-model="dataForm.btnLineNum">
              <el-option :label="3" :value="3"></el-option>
              <el-option :label="4" :value="4"></el-option>
            </el-select>
          </tip-form-item>
          <el-form-item label="小区简码" prop="linkCode" v-if="!batchAdd">
            <el-input v-model="dataForm.linkCode"></el-input>
          </el-form-item>
          <el-form-item label="wifi账号" prop="wifiName" v-if="!batchAdd">
            <el-input v-model="dataForm.wifiName"></el-input>
          </el-form-item>
          <el-form-item label="wifi密码" prop="wifiPwd" v-if="!batchAdd">
            <el-input v-model="dataForm.wifiPwd"></el-input>
          </el-form-item>
        </el-row>

        <el-row v-if="batchAdd">
          <div class="tit">
            <h2 style="display: flex; align-items: center">
              呼叫器
              <el-cascader placeholder="请选择XX栋XX单元XX层" v-model="buildingIdSet"
                           style="margin-left: 20px; width: 300px"
                           size="medium" :props="{ value: 'id', label: 'name', checkStrictly: true }"
                           :options="buildingFloors"
                           filterable clearable @change="handleTableGenerator"/>
              <el-button icon="el-icon-download" size="small" plain type="warning" style="margin-left: 10px"
                         @click="handleDownloadTemplate">下载模版
              </el-button>
              <el-upload v-if="buildingIdSet.length > 0"
                         style="display: inline-block; transform: translateY(-3px); margin-left: 10px" action="#"
                         :on-change="handleImport" :show-file-list="false"
                         accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                         :auto-upload="false">
                <el-button icon="el-icon-plus" size="small" plain type="success">导入</el-button>
              </el-upload>
              <el-button icon="el-icon-plus" size="small" plain type="success" v-else @click="handleImport">导入
              </el-button>
            </h2>
            <el-button plain type="success" icon="el-icon-plus" circle @click="addBeeperItem()"></el-button>
          </div>
          <el-table :data="dataForm.list" max-height="800" style="width: fit-content; max-width: fit-content">
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button plain type="danger" icon="el-icon-minus" circle @click="subBeeperItem(scope.$index)">
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="门牌号" align="center" width="300">
              <template slot-scope="scope">
                <el-input disabled="" v-model.trim="scope.row.houseNumber" placeholder="请输入门牌号"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="呼叫器名称" align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model.trim="scope.row.name" placeholder="请输入呼叫器名称"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="wifi账号" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model.trim="scope.row.wifiName" placeholder="请输入wifi账号"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="wifi密码" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model.trim="scope.row.wifiPwd" placeholder="请输入wifi密码"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="小区简码" align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model.trim="scope.row.linkCode" placeholder="请输入小区简码"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-row>
          <div class="tit">
            <h2>服务模板</h2>
          </div>
          <el-col>
            <div class="search_wrap">
              <el-form :inline="true" :model="filters" class="demo-form-inline module-form" ref="searchForm">
                <el-form-item prop="modelName">
                  <el-input v-model="filters.modelName" clearable placeholder="模板名称"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" type="primary" size="small" @click="onSearchModel">查询</el-button>
                  <!--<el-button icon="el-icon-refresh-left" size="small" @click="resetFormModel">重置</el-button>-->
                </el-form-item>
                <el-form-item>
                  <el-button type="success" plain size="small" @click="handleSelectModel">确定使用模板</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>

          <el-table ref="modelList" :max-height="800" :data="filterServerModelList" style="margin-top: 20px"
                    @selection-change="handleSelectionChange" @row-click="$refs.modelList.toggleRowSelection($event)"
                    v-loading="listLoading" element-loading-text="数据加载中，请稍后..."
                    empty-text="对不起，没有找到相关数据">
            <el-table-column type="selection" width="50" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column align="center" label="模板名称" prop="modelName" width="220"></el-table-column>
            <el-table-column align="center" label="模板类型" width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.modelType === 1">常规版</div>
                <div v-if="scope.row.modelType === 2">自由版</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="默认模板" width="100">
              <template slot-scope="scope">
                <div>
                  <el-tag size="mini" effect="dark" v-if="scope.row.defaultFlag === 1"> 是</el-tag>
                  <el-tag size="mini" effect="dark" v-if="scope.row.defaultFlag === 0" type="info"> 否</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="地址" prop="address"></el-table-column>
            <el-table-column align="center" label="推广员申请码" v-if="!batchAdd">
              <template slot-scope="scope">
                <el-select v-model="scope.row.stackId" @focus="handleStackModelFoucs(scope.row)"
                           @change="handleStackModelSelect(scope.row)" clearable filterable>
                  <el-option v-for="item in scope.row.stackList" :value="item.id" :label="item.name + '-' + item.value"
                             :key="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-row v-if="dataForm.serverModelId" style="width: max-content; max-width: calc(100vw - 300px)">
          <div class="tit">
            <h2>服务功能键信息</h2>
            <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn"></el-button>
          </div>
          <el-table :max-height="800" :data="dataForm.beeperBtnList" style="margin-top: 20px">
            <el-table-column label="操作" width="120" align="center" fixed>
              <template slot-scope="scope">
                <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn"></el-button>
                <el-button icon="el-icon-minus" type="danger" plain size="medium" @click="subBtn(scope.$index)" circle>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="功能键编号" width="100" align="center" fixed>
              <template slot-scope="scope">
                <el-input type="number" @input="handleServerCodeInput(scope.$index, scope.row.btnCode)"
                          v-model.trim="scope.row.btnCode" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="服务功能键" width="200" align="center" fixed>
              <template slot-scope="scope">
                <el-select v-model="scope.row.btnId" @focus="getServerBtnList(scope.row.btnId)" clearable filterable>
                  <el-option v-for="item in serverBtnList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="自定义功能键图片" width="160" align="center">
              <template slot-scope="scope">
                <div class="add-img" v-if="!scope.row.customImage" @click="handleSelectImg(scope.$index)">
                  <span class="el-icon-plus"></span>
                </div>
                <el-image @click.native="handleSelectImg(scope.$index)" fit="cover" :src="scope.row.customImage"
                          v-else></el-image>
              </template>
            </el-table-column>
            <el-table-column label="自定义功能键名称" width="130" align="center">
              <template slot-scope="{ row }">
                <el-input v-model="row.customName" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="功能键描述" width="220" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.describes"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="按键归类" width="220" align="center">
              <template slot-scope="scope">
                <el-cascader v-model="scope.row.moduleCodes" clearable filterable :options="btnMRelationList" :props="{
                  children: 'btnFormats',
                  value: 'code',
                  label: 'name',
                }"></el-cascader>
                <!-- <el-select v-model="scope.row.BBB">
                  <el-option v-for="item in homeLayoutDetailList" :label="item.name" :value="item.id" :key="item.id"></el-option>
                </el-select> -->
              </template>
            </el-table-column>
            <el-table-column label="关联类型" width="200" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.relationType" @change="handleRelationTypeChange(scope.row)">
                  <el-option v-for="item in $Options.relationTypeList" :label="item.name" :value="item.id"
                             :key="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="事件类型" width="230" align="center">
              <template slot-scope="scope">
                <el-select v-show="showColumn(scope.row, 1)" @change="handleEventChange(scope.row)"
                           v-model="scope.row.eventId" placeholder="请选择事件" filterable clearable>
                  <el-option v-for="item in getEventList(scope.row)" :value="item.id" :label="item.name" :key="item.id">
                  </el-option>
                </el-select>
                <span v-show="!showColumn(scope.row, 1)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="关联内容" width="350" align="center">
              <template slot-scope="scope">
                <template v-if="showColumn(scope.row, 2)">
                  <el-cascader v-if="scope.row.eventId === 7" style="width: 100%" filterable clearable
                               v-model="scope.row.linkUrl" :options="residentAddressList"
                               :props="{ value: 'id', label: 'name', checkStrictly: true }"
                               placeholder="请选择栋单元层">
                  </el-cascader>
                  <el-select v-else-if="scope.row.eventId === 51" v-model="scope.row.linkUrl" style="width: 100%"
                             placeholder="请选择模板">
                    <el-option v-for="item in serverModelList" :value="item.modelId" :label="item.modelName"
                               :key="item.modelId"></el-option>
                  </el-select>
                  <el-select v-else-if="scope.row.eventId === 55" style="width: 100%" v-model="scope.row.linkUrl"
                             placeholder="请选择设备类型">
                    <el-option v-for="item in $Options.equipmentType" :value="item.key" :label="item.value"
                               :key="item.key"/>
                  </el-select>
                  <el-select v-else-if="scope.row.eventId == 57" style="width: 100%" v-model="scope.row.linkUrl"
                             placeholder="请选择内容">
                    <el-option value="1" label="物业"></el-option>
                    <el-option value="2" label="用户"></el-option>
                  </el-select>
                  <el-input v-else v-model="scope.row.linkUrl"
                            :placeholder="scope.row.eventId === 52 ? '电话号码/内容' : '请输入关联内容'"></el-input>
                </template>
                <span v-else="!showColumn(scope.row, 2)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="服务分类" width="300" align="center">
              <template slot-scope="scope">
                <!-- <el-select
                  v-show="showColumn(scope.row, 3)"
                  placeholder="请选择服务分类"
                  v-model="scope.row.classifyIds"
                  style="width: 280px"
                  multiple
                  clearable
                  filterable
                  @change="handleServerClassifyChange(scope.$index)"
                >
                  <el-option v-for="item in serverClassifyList" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                </el-select> -->
                <el-cascader filterable @change="handleServerClassifyChange(scope.$index)"
                             v-show="showColumn(scope.row, 3)" v-model="scope.row.classifyIds"
                             placeholder="请选择服务分类"
                             :options="serverClassifyList"
                             :props="{ multiple: true, value: 'id', label: 'name', emitPath: false }"
                             clearable :show-all-levels="false"></el-cascader>
                <span v-show="!showColumn(scope.row, 3)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="商户" align="center" width="300">
              <template slot-scope="scope">
                <el-select v-show="showColumn(scope.row, 4)" style="width: 280px" multiple placeholder="请选择商户"
                           v-model="scope.row.businessIdList" clearable filterable
                           @change="handleBusinessChange(scope.$index)"
                           @focus="handleBusinessFocus(scope.row, scope.$index)">
                  <el-option v-for="item in scope.row.businessList" :key="item.name" :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
                <span v-show="!showColumn(scope.row, 4)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="仅会员购买" align="center" width="200">
              <template slot-scope="scope">
                <el-switch v-show="showColumn(scope.row, 5)" v-model="scope.row.limitType" :active-value="1"
                           :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
                <span v-show="!showColumn(scope.row, 5)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="支持语音下单" align="center" width="200">
              <template slot-scope="scope">
                <el-switch v-show="showColumn(scope.row, 6)" v-model="scope.row.voiceOrderFlag" :active-value="1"
                           :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
                <span v-show="!showColumn(scope.row, 6)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="服务时间范围" width="300" align="center">
              <template slot-scope="{ row }"
                        v-if="row.eventId !== 57 && row.eventId !== 58 && row.eventId !== 59 && row.eventId !== 60 && row.eventId !== 61">
                <div class="server-time-range">
                  <el-time-picker placeholder="开始时间" v-model="row.beginServerTime" value-format="HH:mm"
                                  format="HH:mm"></el-time-picker>
                  <span class="separate"></span>
                  <el-time-picker placeholder="结束时间" v-model="row.endServerTime" value-format="HH:mm"
                                  format="HH:mm"></el-time-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="合并功能键编号" align="center" width="130px">
              <template slot-scope="{ row }">
                <span
                    v-if="row.eventId === 6 || row.eventId === 55 || row.eventId === 57 || row.eventId === 58 || row.eventId === 60">#</span>
                <el-input v-else v-model="row.parentBtnCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <div v-show="showColumn(scope.row, 4)">
                  <el-button plain size="mini" type="primary"
                             @click.native="handleOperateMore(scope.row, scope.$index)">
                    编辑
                  </el-button>
                </div>
                <span v-show="!showColumn(scope.row, 4)"> # </span>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row type="flex" justify="center">
          <el-button v-if="userRole === 1 && detailRole === 1 && !equipState && !batchAdd" plain type="success"
                     @click="sureClick(1)">自定义保存
          </el-button>
          <el-button plain type="primary" @click="sureClick(0)">保 存</el-button>
          <el-button plain @click="returnList">取 消</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 产品选择器 -->
    <server-select ref="ServerSelect" @saveServerData="saveServerData"></server-select>
    <!-- 图片选择 -->
    <ImageSelect fileType="1" :show="imageSelect.show" :limit="1" @cancel="imageSelect.show = false"
                 @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import BeeperApi from '@/api/equip/beeper';
import VillageAreaApi from '@/api/address/villageArea';
import VillageApi from '@/api/address/village';
import BusinessApi from '@/api/business/business';
import ServerClassifyApi from '@/api/server/serverClassify';
import ServerBtnApi from '@/api/server/serverBtn';
import ServerTemplateApi from '@/api/server/serverTemplate';
import BeeperClassifyApi from '@/api/equip/beeperClassify';
import PromoteModelApi from '@/api/operation/promoteModel';
import Region from '@/components/Region';
import ServerSelect from '@/components/ServerSelect';
import {getStorage} from '@/utils/auth';
import {USER_INFO} from '@/constants/storeName';
import importExcel from '@/excel/importExcel';
import SalesmanApi from '@/api/business/salesman';
import BtnModelApi from '@/api/operation/btnModel';
import ImageSelect from '@/components/ImageSelect.vue';
import UploadImg from '@/components/UploadImg';
import exportExcel from '@/excel/exportExcel';
import {linkWayList} from "@/enum"

export default {
  name: 'BeeperAdd',
  data() {
    return {
      title: '',
      batchAdd: false,
      dataForm: {
        equipPhone: '',
        openSearch: 0,
        beeperId: '',
        equipName: '',
        beeperType: '',
        linkWay: '',
        beeperVersion: '',
        classifyId: '',
        saleUserId: '',
        defaultOpen: 1,
        btnLineNum: 3,
        helpFlag:1,
        equipCode: '',
        equipMac: '',
        villageId: '',
        villageName: '',
        streetIds: [],
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        areaId: '',
        areaName: '',
        streetId: '',
        streetName: '',
        residentAddress: [], // 栋单元层
        // buildId:"",
        // buildName:"",
        // unitId:"",
        // unitName:"",
        // floorId:"",
        // floorName:"",
        houseNumber: '',
        longitude: '',
        latitude: '',
        wifiName: '',
        wifiPwd: '',
        linkCode: '',
        serverModelId: '',
        serverUpdate: '',
        stackId: '',
        addressType: '',
        address: '',
        requireAddress: 2,
        btnModelId: '', // 按键样式模板id
        btnVoiceFlag: '',
        siteUrl: '',

        btnStyle: '', // 精选是否用新的样式 1是 0否
        beeperBtnList: [
          //服务信息列表
          // {
          //     btnCode:"",
          //     describes:"",
          //     classifyIds:"", //发送类别放在这里发送请求的时候过滤掉
          //     btnId:"",
          //     moduleCodes:[], // 按键样式模板关联id
          //     relationType:"", //案件类型 1.产品 2.H5连接 3.小程序连接
          //     linkUrl:"",
          //     classifyList:[], // 服务分类的列表，提交的时候过滤掉
          //     businessIdList:"",
          //     businessList:[], //商品列表放在这里，提交的时候过滤掉
          //     btnGoodsParams:[] //服务选择弹框的表格数据
          // }
        ],
        showLevel: 1,
        list: [
          {
            name: '',
            residentAddress: null,
            houseNumber: '',
            wifiName: '',
            wifiPwd: '',
            linkCode: '',
          },
        ], //呼叫器批量新增的列表
        customerId: '',
        remark: '',
      },
      linkWayLists: linkWayList,
      initBeeperBtnList: [], //这个是编辑的时候保存服务信息列表数据，不会改变
      userList: [],
      filters: {
        modelName: '',
        // streetIds: [],
        // provinceId: "",
        // cityId: "",
        // areaId: "",
        // streetId: "",
        // villageId: '',
      },
      roleRules: {
        equipName: [
          {required: true, message: '请输入呼叫器名称', trigger: 'blur'},
          {max: 20, message: '长度不超过20个字', trigger: 'blur'},
        ],
        address: [{required: true, message: '请补充详细地址', trigger: 'blur'}],
        beeperType: [{required: true, message: '请选择呼叫器类型', trigger: 'change'}],
        linkWay: [{required: true, message: '请选择连网方式', trigger: 'change'}],
        beeperVersion: [{required: true, message: '请选择呼叫器版本', trigger: 'change'}],
        addressType: [{required: true, message: '请选择地址类型', trigger: 'change'}],
        streetIds: [{required: true, message: '请选择地区', trigger: 'change'}],
        villageId: [{required: true, message: '请选择小区', trigger: 'change'}],
        residentAddress: [{required: true, message: '请选择栋单元层', trigger: 'change'}],
        houseNumber: [{required: true, message: '请输入门牌号', trigger: 'blur'}],
      },
      isShow: false,
      listLoading: false,
      userRole: '',
      detailRole: '',
      loading: false,
      selectedList: [], //
      modelVillageList: [], //小区列表
      villageList: [], //小区列表
      serverModelList: [], //模板列表
      serverBtnList: [], //服务功能按键
      serverClassifyList: [], //二级分类集合
      // listLength:99, //服务信息最多可添加的数量
      saleUserList: [], //业务员列表
      beeperTypeList: [
        //呼叫器类型列表
        {id: 1, name: '公共'},
        {id: 2, name: '专属'},
      ],
      beeperVersionList: [
        // 呼叫器版本（1.虚拟版 2.基础版 3.智能版 4.触屏版 ）
        {id: 1, name: '虚拟版'},
        {id: 2, name: '基础版'},
        {id: 3, name: '智能版'},
        {id: 4, name: '119报警版'},
        {id: 5, name: '110报警版'},
        {id: 6, name: '120急救版'},
        {id: 7, name: '综合报警版'},
        {id: 8, name: '物业版'},
      ],
      defaultOpenList: [
        {id: 1, name: '精选'},
        {id: 2, name: '全部'},
      ],
      showLevelList: [
        {id: 1, name: '仅精选'},
        {id: 0, name: '全部'},
      ],
      beeperClassifyList: [],
      allEventList: [],
      imageSelect: {
        show: false,
        index: '',
      },
      btnModelList: [],
      btnMRelationList: [],
      residentAddressList: [],
      buildingIdSet: [], // 楼栋层id
      buildingFloors: [], // 楼栋层数组
    };
  },
  mounted() {
    this.init();
  },
  activated() {
  },
  watch: {
    'dataForm.showLevel': {
      handler(val) {
        if (val) {
          this.dataForm.defaultOpen = 1;
        }
      },
      immediate: true,
    },
    'dataForm.addressType': {
      handler(val) {
        if (val === 1 || val === 3) this.dataForm.requireAddress = 2;
      },
    },
  },
  computed: {
    equipState() {
      return this.$route.query.hasOwnProperty('equipState');
    },
    filterServerModelList() {
      return this.serverModelList.filter((item) => !item.disabled);
    },
  },
  components: {
    Region,
    ServerSelect,
    ImageSelect,
    UploadImg,
  },

  methods: {
    async init() {
      this.getSaleUserList();
      // 获取服务功能键列表
      this.getServerBtnList();
      this.getServerClassifyList();
      this.getBeeperClassifyList();

      // 获取用户角色
      this.userRole = getStorage(USER_INFO).userRole;
      this.detailRole = getStorage(USER_INFO).detailRole;
      this.title = '新增呼叫器';
      this.allEventList = this.$Options.eventListMap;
      const {id, batchAdd, equipState} = this.$route.query;
      if (id) {
        this.dataForm.beeperId = id;
        this.title = '编辑呼叫器';
        this.getData();
      }

      if (this.$route.query.batchAdd) {
        this.getUserList();
        this.title = '批量新增呼叫器';
        this.batchAdd = batchAdd;
        this.dataForm.beeperType = 1;
        this.dataForm.linkWay = 0;
        this.$delete(this.roleRules, 'equipName');
        this.$delete(this.roleRules, 'beeperVersion');
        this.$delete(this.roleRules, 'residentAddress');
        this.$delete(this.roleRules, 'houseNumber');
        this.$set(this.roleRules, 'customerId', [{required: true, message: '请选择主用户', trigger: 'change'}]);
        this.$set(this.roleRules, 'streetIds', [{required: true, message: '请选择地区', trigger: 'change'}]);
        this.$set(this.roleRules, 'villageId', [{required: true, message: '请选择小区', trigger: 'blur'}]);
        this.$set(this.roleRules, 'saleUserId', [{required: true, message: '请选择业务员', trigger: 'change'}]);
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate();
        });
      }
    },
    keydown(e) {
      if (e.keyCode === 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      var cond = {
        id: this.dataForm.beeperId,
      };
      const res = await BeeperApi.getBeeperInfo(cond);
      this.$Utils.bindingBean(this.dataForm, res.data);
      //这里把地区选项内容整合了 并且方法中只对有设置过得数据进行获取
      this.dataForm.streetIds = [
        this.dataForm.provinceId,
        this.dataForm.provinceName,
        this.dataForm.cityId,
        this.dataForm.cityName,
        this.dataForm.areaId,
        this.dataForm.areaName,
        this.dataForm.streetId,
        this.dataForm.streetName,
      ];
      if (res.data.beeperBtnList && res.data.serverUpdate === 1) {
        this.initBeeperBtnList = [];
        this.dataForm.beeperBtnList = res.data.beeperBtnList.map((item) => {
          const businessIdList = (item.businessList || []).map((item2) => item2.id) || [];
          let linkUrl = item.linkUrl;
          if (linkUrl) {
            if (item.eventId === 7) {
              linkUrl = item.linkUrl.split(',').map((item2) => Number(item2));
            } else if (item.eventId === 51) {
              linkUrl = Number(item.linkUrl);
            }
          }
          item.serverTimeRange && (item.serverTimeRange = item.serverTimeRange.split(','));

          const obj = {
            btnId: item.btnId,
            btnCode: item.btnCode,
            describes: item.describes,
            moduleCode: item.moduleCode,
            formatCode: item.formatCode,
            customImage: item.customImage,
            customName: item.customName,
            relationType: item.relationType,
            parentBtnCode: item.parentBtnCode,
            limitType: item.limitType,
            linkUrl,
            eventId: item.eventId || '',
            classifyIdList: item.classifyIdList || [],
            businessIdList,
            voiceOrderFlag: item.voiceOrderFlag,
            btnGoodsParams: item.btnGoodsParams,
            // serverTimeRange:item.serverTimeRange,
            beginServerTime: item.serverTimeRange ? item.serverTimeRange[0] : '',
            endServerTime: item.serverTimeRange ? item.serverTimeRange[1] : '',
            residentAddress: [item.buildId, item.unitId, item.floorId, item.houseNumberId].filter((item) => item),
          };
          this.initBeeperBtnList.push(obj);
          return {
            beeperId: item.beeperId,
            classifyIds: obj.classifyIdList,
            businessList: item.businessList,
            moduleCodes: [item.moduleCode, item.formatCode].filter((item) => item),
            ...obj,
          };
        });
        this.initBeeperBtnList = JSON.parse(JSON.stringify(this.initBeeperBtnList));
      } else if (!res.data.beeperBtnList && res.data.serverUpdate === 0 || res.data.beeperBtnList && res.data.serverUpdate === 0) {
        if (res.data.serverModelId) {
          this.getServerTemplateBtn()
        }
      }

      if (res.data.serverModelId) {
        // 这里还需要把stackId添加进去
        let stackList = [];
        if (res.data.stackId && res.data.stackInfo) {
          const arr = res.data.stackInfo.split('-');
          stackList = [{id: res.data.stackId, name: arr[0], value: arr[1]}];
        }
        this.serverModelList = [
          {
            modelId: res.data.serverModelId,
            modelName: res.data.modelName,
            stackId: res.data.stackId,
            stackList,
          },
        ];
        this.$nextTick(() => {
          this.$refs.modelList.toggleRowSelection(this.serverModelList[0], true);
        });
      }

      // 以下需要根据id与name生成下拉列表，因为下拉列表的下拉选择数据是点击下拉框的时候才请求接口获取到的
      // 所以编辑的时候需要自己拼接一条数据
      // 有值的时候才拼接数据
      if (res.data.btnModelId) {
        // 存在按键样式模板,按键样式列表
        this.getBtnModelInfo();
      }
      if (res.data.villageId) {
        this.villageList = [{id: res.data.villageId, name: res.data.villageName}];
        this.dataForm.residentAddress = [res.data.buildId, res.data.unitId, res.data.floorId, res.data.houseNumberId].filter((item) => item);
        this.getResidentAddressList();
        this.getModelList();
      }
    },
    // 获取按键样式模板列表
    async getBtnModelInfo() {
      const id = this.dataForm.btnModelId;
      if (!id) return;
      let {data} = await BtnModelApi.getBtnModel({id});
      this.btnMRelationList = data.btnModelRelations || [];
      this.formatBtnMRelationList();
    },
    formatBtnMRelationList() {
      this.btnMRelationList.forEach((item, index) => {
        if (item.btnFormats && item.btnFormats.length) {
          item.btnFormats.forEach((item2) => {
            this.$set(item2, 'code', item2.formatCode);
            this.$set(item2, 'name', `${item2.row}行${item2.col}列`);
          });
        }
        this.$set(item, 'code', item.moduleCode);
        this.$set(item, 'name', `${this.$Filters.formatModuleType(item.moduleType)}模块`);
      });
    },
    getUserList() {
      BeeperApi.customerList().then((res) => {
        this.userList = res.data.filter((item) => item.value);
      });
    },
    getSaleUserList() {
      SalesmanApi.getSalesmanIdName().then((res) => {
        this.saleUserList = res.data;
      });
    },
    addBeeperItem() {
      const {list} = this.dataForm;
      list.push({
        name: '',
        residentAddress: null,
        houseNumber: '',
        wifiName: '',
        wifiPwd: '',
        linkCode: '',
      });
    },
    subBeeperItem(index) {
      const {list} = this.dataForm;
      list.splice(index, 1);
    },

    /**
     * 通过excel 导入呼叫器
     * @param file
     * @returns {Promise<void>}
     */
    async handleImport(file) {
      if (this.buildingIdSet.length === 0) {
        this.$Utils.notifyWarn('请先选择楼栋层');
        return false;
      }

      const {dataForm} = this;
      let res = await importExcel(file, 0, ['houseNumber', 'name', 'wifiName', 'wifiPwd', 'linkCode']);
      res = res || [];

      res.forEach((item) => {
        const find = this.dataForm.list.find((c) => c.houseNumber === item.houseNumber);
        const findIndex = this.dataForm.list.findIndex((c) => c.houseNumber === item.houseNumber);
        if (find && findIndex !== -1) {
          const {linkCode, name, wifiName, wifiPwd} = item;
          this.$set(this.dataForm.list, findIndex, {
            ...this.dataForm.list[findIndex],
            linkCode,
            name,
            wifiName,
            wifiPwd,
          });
        }
      });
    },

    getBeeperClassifyList() {
      BeeperClassifyApi.beeperClassifyList().then((res) => {
        this.beeperClassifyList = res.data;
      });
    },
    saveServerData(obj) {
      this.dataForm.beeperBtnList[obj.index].btnGoodsParams = obj.tableData.filter((item) => item.serverNo);
    },
    // 关联类型改变,全部要清空
    handleRelationTypeChange(row) {
      row.eventId = '';
      row.linkUrl = '';
      row.voiceOrderFlag = 0;
      row.classifyIds = [];
      row.businessIdList = [];
      row.btnGoodsParams = [];
      row.businessIdList = [];
    },
    // 事件全部改变
    handleEventChange(row) {
      row.linkUrl = '';
      row.voiceOrderFlag = 0;
      row.classifyIds = [];
      row.businessIdList = [];
      row.btnGoodsParams = [];
      row.businessIdList = [];
    },
    /**
     * 根据关联类型来判断是否显示这一列
     * @param type 1表示事件类型 2表示关联内容 3表示服务分类 4表示商户、操作 5表示仅会员购买
     */
    showColumn(row, type) {
      const {relationType, eventId} = row;
      switch (type) {
        case 1:
          return relationType == 1 || relationType == 4 || relationType == 5;
        case 2:
          return relationType == 1 || relationType == 2 || relationType == 3 || eventId == 2 || eventId == 7 || eventId == 51 || eventId == 52 || eventId == 54 || eventId === 55 || eventId === 57;
        case 3:
          return relationType == 1 || eventId == 3 || eventId == 5 || eventId == 7 || eventId == 60;
        case 4:
          return (relationType == 1 || eventId !== 56) && eventId !== 55 && eventId !== 57 && eventId !== 58 && eventId !== 59 && row.eventId !== 61;
        case 5:
          return relationType == 1;
        case 6:
          return eventId == 10 || eventId == 18 || eventId == 19;
      }
    },
    // 选择图片
    handleSelectImg(index) {
      this.imageSelect.show = true;
      this.imageSelect.index = index;
    },
    getUrlList([val]) {
      const {
        imageSelect,
        dataForm: {beeperBtnList},
      } = this;
      imageSelect.show = false;
      beeperBtnList[imageSelect.index].customImage = val.url;
    },
    // 获取服务分类列表
    getEventList(row) {
      return this.allEventList[row.relationType];
    },
    addBtn() {
      let arr = [];
      let btnCode = 0;
      this.dataForm.beeperBtnList.forEach((item) => {
        if (item.btnCode) {
          arr.push(Number(item.btnCode));
        }
      });
      arr.sort((a, b) => a - b);

      while (true) {
        btnCode++;
        if (btnCode != arr[btnCode - 1]) {
          break;
        }
      }
      this.dataForm.beeperBtnList.push({
        btnCode: String(btnCode),
        describes: '',
        btnId: '',
        customImage: '',
        customName: '',
        parentBtnCode: '',
        limitType: 0,
        relationType: 1,
        linkUrl: '',
        voiceOrderFlag: 0,
        eventId: 10,
        classifyIds: [],
        businessIdList: [],
        businessList: [],
        moduleCodes: [],
        beginServerTime: '',
        endServerTime: '',
        // serverTimeRange:null
      });
    },
    subBtn(index) {
      this.dataForm.beeperBtnList.splice(index, 1);
    },
    // 根据关键字查询模板
    onSearchModel() {
      const {
        serverModelList,
        filters: {modelName},
      } = this;
      const tempArr = this.selectedList.map((item) => {
        return {
          modelId: item.modelId,
          stackId: item.stackId,
          stackList: item.stackList,
        };
      });
      serverModelList.forEach((item, index) => {
        item.modelName.includes(modelName) ? this.$delete(item, 'disabled') : this.$set(item, 'disabled', true);
        const val = tempArr.find((item2) => item2.modelId == item.modelId);
        if (val) {
          item.stackId = val.stackId;
          item.stackList = val.stackList;
          this.$nextTick(() => {
            this.$refs.modelList.toggleRowSelection(this.serverModelList[index], true);
          });
        }
      });
      // if(!this.dataForm.villageId){
      //   this.serverModelList = []
      //   return
      // }
      // this.listLoading = true
      // this.getModelList();
    },
    // resetFormModel() {
    //   this.$refs.searchForm.resetFields();
    // },
    async getModelList() {
      const {provinceId, cityId, areaId, villageId} = this.dataForm;
      if (!villageId) return (this.serverModelList = []);
      var cond = {
        provinceId,
        cityId,
        areaId,
        villageId,
      };
      // 发送请求
      try {
        const {data} = await ServerTemplateApi.listModel(cond);
        // .then(res => {
        this.listLoading = false;
        // 重新获取模板列表时候要对比原来的值
        const tempArr = this.selectedList.map((item) => {
          return {
            modelId: item.modelId,
            stackId: item.stackId,
            stackList: item.stackList,
          };
        });
        this.serverModelList = data || [];
        this.serverModelList.forEach((item, index) => {
          this.$set(item, 'stackId', '');
          this.$set(item, 'stackList', []);
          let val = tempArr.find((item2) => item.modelId == item2.modelId);
          if (val) {
            item.stackId = val.stackId;
            item.stackList = val.stackList;
            this.$nextTick(() => {
              this.$refs.modelList.toggleRowSelection(this.serverModelList[index], true);
            });
          }
        });
      } finally {
        this.listLoading = false;
      }
      // }).catch(err => {
      //   _this.listLoading = false
      // })
    },
    handleSelectionChange(value) {
      this.selectedList = value;
    },
    async handleSelectModel() {
      if (!this.selectedList || this.selectedList.length < 1) {
        this.$message.error('请至少选择一个服务模板');
        return;
      }
      this.$message.success('模板使用成功');
      this.dataForm.serverModelId = this.selectedList[0].modelId;
      this.dataForm.stackId = this.selectedList[0].stackId;
      this.dataForm.btnModelId = this.selectedList[0].btnModelId;
      this.dataForm.btnStyle = this.selectedList[0].btnStyle;
      this.dataForm.btnVoiceFlag = this.selectedList[0].btnVoiceFlag;
      this.getServerTemplateBtn();
      this.getBtnModelInfo();
    },
    async getServerTemplateBtn() {
      const res = await ServerTemplateApi.getServerTemplateBtn({
        modelId: this.dataForm.serverModelId,
      });
      const data = res.data || [];
      this.dataForm.beeperBtnList = data.map((item) => {
        item.serverTimeRange && (item.serverTimeRange = item.serverTimeRange.split(','));
        return {
          btnCode: item.btnCode,
          describes: item.describes,
          btnId: item.btnId || '',
          customImage: item.customImage || '',
          customName: item.customName,
          relationType: item.relationType,
          linkUrl: item.eventId == 7 && item.linkUrl ? item.linkUrl.split(',').map((item) => Number(item)) : item.linkUrl,
          voiceOrderFlag: item.voiceOrderFlag,
          eventId: item.eventId,
          classifyIds: item.classifyIdList || [],
          businessIdList: (item.businessList && item.businessList.map((item) => item.id)) || [],
          businessList: item.businessList || [],
          btnGoodsParams: item.btnGoodsParams || [],
          parentBtnCode: item.parentBtnCode || '',
          limitType: item.limitType,
          beginServerTime: item.serverTimeRange ? item.serverTimeRange[0] : '',
          endServerTime: item.serverTimeRange ? item.serverTimeRange[1] : '',
          moduleCodes: [item.moduleCode, item.formatCode].filter((item) => item),
        };
      });
    },
    handleViewModelInfo(id) {
      let _this = this;
      _this.$router.push({
        path: '/server/serverTemplateDetail',
        query: {id: id},
      });
    },
    // 获取服务分类列表
    handleServerClassifyFocus(row) {
      let params = {};
      if (row.classifyIds.length > 0) {
        let flag = row.classifyIds.some((item) => row.classifyList.some((item2) => item2.id == item && item2.state == 1));
        params = {
          openFlag: flag ? 1 : 0,
        };
      }
      ServerClassifyApi.listIdName(params).then((res) => {
        row.classifyList = res.data;
      });
    },
    // 获取服务功能键列表
    getServerBtnList(id) {
      let params = {btnType: 1};
      if (id) {
        let filterIds = this.dataForm.beeperBtnList
            .filter((item) => item.btnId && item.btnId != id)
            .map((item) => item.btnId)
            .join(',');
        if (filterIds) {
          params.filterIds = filterIds;
        }
      }
      ServerBtnApi.serverBtnList(params).then((res) => {
        this.serverBtnList = res.data;
      });
    },
    // 获取产品分类列表
    getServerClassifyList() {
      let param = {level: -2}
      ServerClassifyApi.listServerClassifyTree(param).then(res => {
        this.serverClassifyList = res.data
      })
    },
    // 点击编辑操作弹框数据
    handleOperateMore(row, index) {
      if (row.businessIdList.length === 0) {
        this.$message.error('请先填服务分类和商户');
        return;
      }
      let serverBtnParam = this.dataForm.beeperBtnList[index].btnGoodsParams;
      let params = {
        // 只有编辑的时候才会存在beeperId,新增的时候不会存在beeperId,做判断beeperId是否存在，这里不能传undefined
        //beeperId: this.dataForm.beeperBtnList[index].beeperId ? this.dataForm.beeperBtnList[index].beeperId : null,
        beeperId: this.dataForm.beeperId ? this.dataForm.beeperId : null,
        modelId: this.dataForm.beeperId ? null : this.dataForm.serverModelId,
        provinceId: this.dataForm.provinceId,
        cityId: this.dataForm.cityId,
        areaId: this.dataForm.areaId,
        villageId: this.dataForm.villageId,
        classifyIds: row.classifyIds.join(','),
        businessIds: row.businessIdList.join(','),
        name: '',
        parentBtnCode: row.parentBtnCode,
        btnId: row.btnId,
      };
      if (this.$Hooks.isDockingEvent(row.eventId)) {
        params.dockingFlag = 2;
        params.dockingType = row.eventId == 18 ? 1 : row.eventId == 19 ? 2 : '';
      }
      let moduleType = '';
      if (row.moduleCodes[0]) {
        moduleType = this.btnMRelationList.find((item) => item.moduleCode == row.moduleCodes[0]).moduleType;
      }
      this.$refs.ServerSelect.showDialog({
        params,
        moduleType,
        serverBtnParam,
        index,
        businessList: row.businessList,
        btnGoodsParams: row.btnGoodsParams,
      });
    },
    // 服务分类选择框改变值的时候调用的函数,
    handleServerClassifyChange(index) {
      this.dataForm.beeperBtnList[index].businessIdList = [];
      this.dataForm.beeperBtnList[index].businessList = [];
      this.dataForm.beeperBtnList[index].btnGoodsParams = [];
      // this.dataForm.beeperBtnList[index].btnGoodsParams = []
    },

    // 商户选择框改变值的时候调用的函数
    handleBusinessChange(index) {
      let obj = this.dataForm.beeperBtnList[index];
      let businessList = this.dataForm.beeperBtnList[index].businessIdList;
      obj.btnGoodsParams = obj.btnGoodsParams.filter((item) => businessList.some((item2) => item.businessId == item2));
    },
    // 商户选择框点击聚焦的时候调用的函数
    handleBusinessFocus(row, index) {
      let param = {
        classifyIds: row.classifyIds.join(','),
        type: 2,
      };
      if (this.dataForm.villageId) {
        param.villageId = this.dataForm.villageId;
      }
      if (this.dataForm.provinceId) {
        param.provinceId = this.dataForm.provinceId;
        param.cityId = this.dataForm.cityId;
        param.areaId = this.dataForm.areaId;
      }
      if (param.classifyIds) {
        BusinessApi.listIdName(param).then((res) => {
          this.dataForm.beeperBtnList[index].businessList = res.data;
        });
      }
      this.dataForm.beeperBtnList = this.dataForm.beeperBtnList;
    },
    // 通过小区获取栋单元层下的数据
    async getResidentAddressList() {
      const {data} = await VillageAreaApi.getListTree({
        villageId: this.dataForm.villageId,
      });
      const resultArray = this.filterTreeByLevels(data, 3);
      this.residentAddressList = data || [];
      this.buildingFloors = resultArray || [];
    },
    handleVillageChange() {
      this.serverModelList = [];
      this.dataForm.serverModelId = '';
      this.dataForm.beeperBtnList = [];
      this.dataForm.stackId = '';
      this.dataForm.villageName = '';
      this.dataForm.residentAddress = [];
      this.residentAddressList = [];
      this.dataForm.beeperBtnList.forEach((item) => {
        (item.eventId == 7 || item.eventId == 51) && (item.linkUrl = '');
      });
      this.batchAdd && this.dataForm.list.forEach((item) => item.residentAddress == null);
      if (!this.dataForm.villageId) return;
      // if (this.dataForm.villageId) {
      this.dataForm.villageName = this.villageList.find((item) => item.id == this.dataForm.villageId).name;
      // 查询可使用的服务模板
      this.getModelList();
      this.getResidentAddressList();

      // 查找该小区下面的楼栋层
    },
    handleVillageFocus() {
      // 点击聚焦小区的时候才发送请求数据
      if (this.dataForm.streetIds.length > 0) {
        let param = {
          provinceId: this.dataForm.provinceId,
          cityId: this.dataForm.cityId,
          areaId: this.dataForm.areaId,
          streetId: this.dataForm.streetId,
          name: '',
        };
        VillageApi.villageList(param).then((res) => {
          this.villageList = res.data;
        });
      }
    },
    // handleModelStreetChange(val) {
    //   // 地区改变要清空小区和设备地址还有列表
    //   this.filters.villageId = ""
    //   this.modelVillageList = []
    //   this.filters.provinceId = val.provinceId;
    //   this.filters.cityId = val.cityId;
    //   this.filters.areaId = val.areaId;
    //   this.filters.streetId = val.streetId;

    //   if (val.provinceId) {
    //     this.filters.streetIds = [
    //       val.provinceId,
    //       val.cityId,
    //       val.areaId,
    //       val.streetId,
    //     ];
    //   } else {
    //     this.filters.streetIds = []
    //   }
    // },
    // handleModelVillageFocus() {
    //   // 点击聚焦小区的时候才发送请求数据
    //   if (this.filters.streetIds.length > 0) {
    //     let param = {
    //       provinceId: this.filters.provinceId,
    //       cityId: this.filters.cityId,
    //       areaId: this.filters.areaId,
    //       streetId: this.filters.streetId,
    //       name: "",
    //     }
    //     VillageApi.villageList(param).then(res => {
    //       this.modelVillageList = res.data
    //     })
    //   }
    // },

    handleStackModelFoucs(row) {
      const {villageId} = this.dataForm;
      if (!villageId) {
        return;
      }
      PromoteModelApi.stackList({serverModelId: row.modelId, villageId}).then((res) => {
        row.stackList = res.data;
      });
    },

    handleStackModelSelect(row) {
      const {modelId, stackId} = row;
      const {serverModelId} = this.dataForm;
      if (serverModelId && serverModelId == modelId) {
        this.dataForm.stackId = stackId;
      }
    },
    handleItemChange(val) {
      // 地区改变要清空小区和设备地址还有列表
      this.dataForm.villageId = '';
      this.dataForm.villageName = '';
      this.villageList = [];
      this.serverModelList = [];
      this.dataForm.serverModelId = '';
      this.dataForm.stackId = '';
      this.dataForm.provinceId = val.provinceId;
      this.dataForm.provinceName = val.provinceName;
      this.dataForm.cityId = val.cityId;
      this.dataForm.cityName = val.cityName;
      this.dataForm.areaId = val.areaId;
      this.dataForm.areaName = val.areaName;
      this.dataForm.streetId = val.streetId;
      this.dataForm.streetName = val.streetName;
      this.dataForm.residentAddress = null;
      this.dataForm.beeperBtnList = [];
      this.residentAddressList = [];
      this.buildingIdSet = [];
      this.buildingFloors = [];

      if (val.provinceId) {
        // 如果地区是删除那么就不用删除列表和设备地址数据
        // this.dataForm.beeperBtnList.forEach(item => {
        //   item.businessIdList = []
        //   item.businessList = []
        //   item.btnGoodsParams = []
        // })
        this.dataForm.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      } else {
        this.dataForm.streetIds = [];
      }
    },
    // 输入功能键编号的时候
    handleServerCodeInput(index, btnCode) {
      let reg = /^[1-9][0-9]*$/;
      if (reg.test(btnCode)) {
        this.dataForm.beeperBtnList[index].btnCode = btnCode;
      } else {
        this.dataForm.beeperBtnList[index].btnCode = '';
      }
    },
    getLngLat(type) {
      if (type == 1) {
        window.open('https://api.map.baidu.com/lbsapi/getpoint/index.html', '_blank');
      } else {
        window.open('https://lbs.qq.com/getPoint', '_blank');
      }
    },
    submitCheck() {
      let {stackId, saleUserId, beeperBtnList, btnStyle, residentAddress} = this.dataForm;

      // 这里处理以下楼栋单元层的地址
      this.residentAddress = this.$Utils.filterTreeToArr(this.residentAddressList, {id: residentAddress.at(-1)}, 'id');

      if (!stackId && !saleUserId) {
        this.$message.error('业务员和推广员申请码至少选择一个');
        return;
      }
      // 判断弹框表格里面是否一个编号都没有写或者一次都没有编辑过)
      for (let i = 0; i < beeperBtnList.length; i++) {
        const {
          btnCode,
          btnId,
          relationType,
          btnGoodsParams,
          eventId,
          moduleCodes,
          parentBtnCode,
          classifyIds,
          businessIdList,
          linkUrl,
          endServerTime,
          beginServerTime
        } = beeperBtnList[i];
        if (!btnCode) {
          this.$message.error('请填写功能键编号');
          return;
        }
        if (beeperBtnList.findIndex((item2) => item2.btnCode == btnCode) != i) {
          this.$message.error('功能键编号重复');
          return;
        }
        if (!btnId) {
          this.$message.error('请选择服务功能键');
          return;
        }
        let message = '';
        switch (relationType) {
          case 1:
            if (!classifyIds.length || !businessIdList.length || !eventId) {
              message = '请完善服务信息';
            } else if (btnGoodsParams?.length && !btnGoodsParams.some((item) => item.serverNo)) {
              message = `功能键编号为${btnCode}的没有编辑填写编号`;
            } else if (btnStyle && !parentBtnCode && !String(moduleCodes)) {
              message = `功能键编号为${btnCode}的没有选择按键归类`;
            }
            break;
          case 2:
          case 3:
            if (!linkUrl) message = '请完善服务信息';
            break;
          case 4:
            if (!eventId || ((eventId == 2 || eventId == 51 || eventId == 52) && !linkUrl)) {
              message = '请完善服务信息';
            } else if (eventId == 6) {
              beeperBtnList[i].parentBtnCode = '';
              if (btnStyle && !String(moduleCodes)) message = `功能键编号为${btnCode}的没有选择按键归类`;
            }
            break;
          case 5:
            if (!eventId || (eventId == 3 && !classifyIds.length) || (eventId == 5 && !classifyIds.length) || (eventId == 54 && !linkUrl)) message = '请完善服务信息';
            break;
        }
        if (message) {
          this.$message.error(message);
          return;
        }

        if ((!beginServerTime && endServerTime) || (beginServerTime && !endServerTime)) {
          beeperBtnList[i].beginServerTime = '';
          beeperBtnList[i].endServerTime = '';
        }
      }
      // 过滤的beeperBtnList里面的businessIdList,businessList、classifyIds,classifyList，记住这里需要用新的一个变量或属性接受
      this.beeperBtnList = beeperBtnList.map((item) => {
        const {relationType, eventId} = item;
        return {
          btnCode: item.btnCode,
          describes: item.describes,
          btnId: item.btnId,
          moduleCode: item.moduleCodes[0] || '',
          formatCode: item.moduleCodes[1] || '',
          customImage: item.customImage,
          customName: item.customName,
          relationType,
          parentBtnCode: item.eventId == 6 ? '' : item.parentBtnCode,
          limitType: relationType == 1 ? item.limitType : 0,
          linkUrl:
              (relationType == 1 || relationType == 2 || relationType == 3 || eventId == 2 || eventId == 7 || eventId == 51 || eventId == 54 || eventId === 55 || eventId === 57) && item.linkUrl
                  ? item.linkUrl.toString()
                  : '',
          voiceOrderFlag: item.eventId == 10 || item.eventId == 18 || item.eventId == 19 ? item.voiceOrderFlag : 0,
          eventId: relationType == 1 || relationType == 4 || relationType == 5 ? item.eventId : '',
          classifyIdList: relationType == 1 || eventId == 3 || eventId == 5 || eventId == 7 || eventId === 60 ? item.classifyIds : [],
          businessIdList: relationType == 1 || (relationType == 5 && eventId == 7) || eventId === 60 ? item.businessIdList : [],
          serverTimeRange: item.beginServerTime ? item.beginServerTime + ',' + item.endServerTime : '',
          btnGoodsParams: relationType == 1 || eventId === 60 ? item.btnGoodsParams : [],
        };
      });
      if (this.batchAdd) {
        // 批量新增做校验
        let {list} = this.dataForm;
        for (let item of list) {
          if (!item.residentAddress) {
            this.$message.error('请填写栋单元层');
            return false;
          }
          if (!item.name) {
            this.$message.error('请填写呼叫器名称');
            return false;
          }
          item.buildId = item.residentAddress.buildId;
          item.buildName = item.residentAddress.buildName;
          item.unitId = item.residentAddress.unitId;
          item.unitName = item.residentAddress.unitName;
          item.floorId = item.residentAddress.floorId;
          item.floorName = item.residentAddress.floorName;
          item.houseNumber = item.residentAddress.houseNumber;
          item.houseNumberId = item.residentAddress.houseNumberId;
        }
        this.beeperList = list;
      }
      return true;
    },
    sureClick(serverUpdate) {
      this.dataForm.serverUpdate = serverUpdate; //决定选择哪个保存
      // 提交
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // 对许多数据进行过滤校验，前端校验
          if (!this.submitCheck()) {
            return;
          }
          let msg = serverUpdate === 1 ? '自定义保存后将不受服务模板的控制，请谨慎保存' : message.MSG_CONFIRM_SAVE_ALTER;

          this.$confirm(msg, '提示', {
            type: serverUpdate === 1 ? 'warning' : '',
          }).then(() => {
            if (this.batchAdd) {
              this.batchAddData();
            } else if (this.dataForm.beeperId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    setLinkway() {
      if (this.dataForm.beeperVersion == 1) {
        this.dataForm.linkWay = 0
      } else {
        this.dataForm.linkWay = ''
      }
    },
    watchLinkway() {
      if (this.dataForm.beeperVersion != 1) {
        if (this.dataForm.linkWay == 0) {
          this.$message.error("非虚拟版呼叫器必须选连网方式")
          this.dataForm.linkWay = ""
        }
      }
    },
    // 编辑的时候判断是否是否修改了某一行数据
    judgeUpdate(obj1, obj2) {
      if (typeof obj1 != 'object' || typeof obj2 != 'object' || obj1 == null || obj2 == null) {
        return !(obj1 == obj2);
      } else {
        if (Array.isArray(obj1)) {
          if (obj1.length == obj2.length && obj1.length != 0) {
            return obj1.some((item, index) => {
              return this.judgeUpdate(item, obj2[index]);
            });
          } else {
            return true;
          }
        } else {
          let flag = [];
          for (let key in obj1) {
            if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
              flag.push(this.judgeUpdate(obj1[key], obj2[key]));
            }
          }
          return flag.some((item) => item);
        }
      }
    },
    editData() {
      // 编辑
      var cond = {
        beeperId: this.dataForm.beeperId,
        siteUrl: this.dataForm.siteUrl,
        equipName: this.dataForm.equipName,
        beeperType: this.dataForm.beeperType,
        linkWay: this.dataForm.linkWay,
        openSearch: this.dataForm.openSearch,
        beeperVersion: this.dataForm.beeperVersion,
        addressType: this.dataForm.addressType,
        // address: this.dataForm.address,
        requireAddress: this.dataForm.requireAddress,
        classifyId: this.dataForm.classifyId,
        defaultOpen: this.dataForm.defaultOpen,
        equipCode: this.dataForm.equipCode,
        equipMac: this.dataForm.equipMac,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        buildId: this.residentAddress[0]?.id,
        buildName: this.residentAddress[0]?.name,
        unitId: this.residentAddress[1]?.id,
        unitName: this.residentAddress[1]?.name,
        floorId: this.residentAddress[2]?.id,
        floorName: this.residentAddress[2]?.name,
        houseNumberId: this.residentAddress[3]?.id,
        houseNumber: this.residentAddress[3]?.name,
        longitude: this.dataForm.longitude,
        latitude: this.dataForm.latitude,
        wifiName: this.dataForm.wifiName,
        linkCode: this.dataForm.linkCode,
        wifiPwd: this.dataForm.wifiPwd,
        beeperBtnList: this.beeperBtnList,
        serverModelId: this.dataForm.serverModelId,
        stackId: this.dataForm.stackId,
        saleUserId: this.dataForm.saleUserId,
        btnLineNum: this.dataForm.btnLineNum,
        btnVoiceFlag: this.dataForm.btnVoiceFlag,
        showLevel: this.dataForm.showLevel,
        btnModelId: this.dataForm.btnModelId,
        btnStyle: this.dataForm.btnStyle,
        remark: this.dataForm.remark,
        equipPhone: this.dataForm.equipPhone,
      };

      if (this.dataForm.serverUpdate) {
        cond.serverUpdate = this.dataForm.serverUpdate;
      }
      this.beeperBtnList.forEach((item, index) => {
        if (this.judgeUpdate(item, this.initBeeperBtnList[index])) {
          this.beeperBtnList[index].isUpdate = 1;
        }
      });

      if (this.$route.query.hasOwnProperty('equipState')) {
        // 是从设备开放池来的就添加设备状态参数
        //cond.equipState = this.$route.query.equipState;
        cond.equipState = 1;
      }
      this.loading = true;
      BeeperApi.editBeeper(cond)
          .then((data) => {
            this.$Utils.notifySuccess();
            this.returnData();
          })
          .catch((err) => {
            err = err.message || err;
            if (err.includes('408')) {
              this.$message.closeAll();
              this.$alert('等待5到10分钟呼叫器新增完成', '提示', {}).then(() => {
                this.returnData();
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    addData() {
      // 新增
      var cond = {
        siteUrl: this.dataForm.siteUrl,
        equipName: this.dataForm.equipName,
        beeperType: this.dataForm.beeperType,
        linkWay: this.dataForm.linkWay,
        openSearch: this.dataForm.openSearch,
        beeperVersion: this.dataForm.beeperVersion,
        addressType: this.dataForm.addressType,
        // address: this.dataForm.address,
        requireAddress: this.dataForm.requireAddress,
        classifyId: this.dataForm.classifyId,
        defaultOpen: this.dataForm.defaultOpen,
        equipMac: this.dataForm.equipMac,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        buildId: this.residentAddress[0]?.id,
        buildName: this.residentAddress[0]?.name,
        unitId: this.residentAddress[1]?.id,
        unitName: this.residentAddress[1]?.name,
        floorId: this.residentAddress[2]?.id,
        floorName: this.residentAddress[2]?.name,
        houseNumberId: this.residentAddress[3]?.id,
        houseNumber: this.residentAddress[3]?.name,
        wifiName: this.dataForm.wifiName,
        wifiPwd: this.dataForm.wifiPwd,
        linkCode: this.dataForm.linkCode,
        beeperBtnList: this.beeperBtnList,
        serverModelId: this.dataForm.serverModelId,
        stackId: this.dataForm.stackId,
        saleUserId: this.dataForm.saleUserId,
        showLevel: this.dataForm.showLevel,
        btnLineNum: this.dataForm.btnLineNum,
        btnVoiceFlag: this.dataForm.btnVoiceFlag,
        btnModelId: this.dataForm.btnModelId,
        btnStyle: this.dataForm.btnStyle,
        remark: this.dataForm.remark,
        equipPhone: this.dataForm.equipPhone,
      };
      if (this.dataForm.serverUpdate) {
        cond.serverUpdate = this.dataForm.serverUpdate;
      }
      this.loading = true;
      BeeperApi.addBeeper(cond)
          .then((data) => {
            this.$Utils.notifySuccess();
            this.returnData();
          })
          .catch((err) => {
            err = err.message || err;
            if (err.includes('408')) {
              this.$message.closeAll();
              this.$alert('等待5到10分钟呼叫器新增完成', '提示', {}).then(() => {
                this.returnData();
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    batchAddData() {
      // 批量新增
      var cond = {
        siteUrl: this.dataForm.siteUrl,
        beeperType: this.dataForm.beeperType,
        linkWay: 0,
        beeperVersion: 1,
        addressType: this.dataForm.addressType,
        classifyId: this.dataForm.classifyId,
        defaultOpen: this.dataForm.defaultOpen,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        beeperBtnList: this.beeperBtnList,
        serverModelId: this.dataForm.serverModelId,
        stackId: this.dataForm.stackId,
        saleUserId: this.dataForm.saleUserId,
        list: this.beeperList,
        customerId: this.dataForm.customerId,
        // address: this.dataForm.address,
        btnModelId: this.dataForm.btnModelId,
        btnStyle: this.dataForm.btnStyle,
        remark: this.dataForm.remark,
      };
      this.loading = true;
      BeeperApi.batchAddBeeper(cond)
          .then((data) => {
            this.$Utils.notifySuccess();
            this.returnData();
          })
          .catch((err) => {
            err = err.message || err;
            if (err.includes('408')) {
              this.$message.closeAll();
              this.$alert('等待5到10分钟呼叫器新增完成', '提示', {}).then(() => {
                // this.returnData()
              });
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    getsiteUrl(val) {
      if (val.length > 0) {
        this.$Utils.notifySuccess('上传成功');
      }
      this.dataForm.siteUrl = val[0];
    },
    returnData() {
      if (this.$route.query.hasOwnProperty('equipState')) {
        // 如果是从设备开放池来的就返回到那里去
        this.$router.push({
          name: 'EquipOpenPoolManagement',
          params: {list: true},
        });
      } else {
        this.$router.push({name: 'BeeperManagement', params: {list: true}});
      }
    },
    returnList() {
      // 返回上一界面
      this.$store.dispatch('delView', this.$route);
      this.$router.back();
      // if (this.$route.query.hasOwnProperty("equipState")) {
      //   // 如果是从设备开放池来的就返回到那里去
      //   this.$router.push({ path: '/equip/equipOpenPoolManagement' })
      // } else {
      //   this.$router.push({ path: '/equip/beeperManagement' })
      // }
    },

    /**
     * 渲染楼栋层模版
     */
    handleTableGenerator() {
      const params = {};
      if (this.buildingIdSet.length === 1) params.buildId = this.buildingIdSet[0];
      if (this.buildingIdSet.length === 2) {
        params.buildId = this.buildingIdSet[0];
        params.unitId = this.buildingIdSet[1];
      }
      if (this.buildingIdSet.length === 3) {
        params.buildId = this.buildingIdSet[0];
        params.unitId = this.buildingIdSet[1];
        params.floorId = this.buildingIdSet[2];
      }
      // 获取门牌号
      VillageAreaApi.ListDetailHouseNumber(params).then((res) => {
        if (res.data) {
          this.dataForm.list = [];
          res.data.forEach((item, index) => {
            this.dataForm.list.push({
              name: '',
              residentAddress: item,
              houseNumber: item.buildName + item.floorName + item.unitName + item.houseNumber,
              wifiName: '',
              wifiPwd: '',
              linkCode: '',
            });
          });
        }
      });
    },

    // 模版下载
    handleDownloadTemplate() {
      if (this.buildingIdSet.length === 0) {
        this.$Utils.notifyWarn('请先选择楼栋层');
        return false;
      }
      const headers = [
        {label: '门牌号（不可修改）', key: 'houseNumber'},
        {label: '呼叫器名称', key: 'name'},
        {label: 'wifi账号', key: 'wifiName'},
        {label: 'wifi密码', key: 'wifiPwd'},
        {label: '小区简码', key: 'linkCode'},
      ];
      exportExcel(headers, this.dataForm.list, '批量新增呼叫器模版');
    },

    /**
     * 处理多余的树结构 level 过滤条件 层数
     * @param tree
     * @param level
     * @returns {*[]}
     */
    filterTreeByLevels(tree, level) {
      return tree.map((node) => {
        const newNode = {...node};
        if (newNode.levels === level) {
          // 如果当前节点的 levels 等于目标级别，将其 children 改为 null
          newNode.children = null;
        } else {
          // 否则，递归处理子节点
          newNode.children = newNode.children ? (newNode.children.length > 0 ? this.filterTreeByLevels(newNode.children, level) : null) : null;
        }
        return newNode;
      });
    },
  },
};
</script>

<style lang="scss">
@import '@/assets/css/views/add.scss';
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss">
.add-img {
  width: 100px;
  height: 100px;
  border: 1px dotted #e5e5e5;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: space-around;
  cursor: pointer;

  .el-icon-plus {
    font-size: 30px;
    color: #e5e5e5;
  }

  .el-image {
    width: 120px;
    height: 120px;
  }
}

.server-time-range {
  display: flex;
  align-items: center;

  .separate {
    width: 20px;
    height: 1px;
    margin: 0 7px;
    background-color: gray;
  }
}

.module-form {
  overflow: hidden;

  .el-form-item {
    .el-cascader {
      width: 310px !important;
    }

    .el-select {
      width: 220px !important;
    }

    width: fit-content !important;
  }
}
</style>
